package ui.media 
{
	import com.gaiaframework.api.Gaia;
	import com.somerandomdude.coordy.layouts.twodee.HorizontalLine;
	import com.somerandomdude.coordy.layouts.twodee.ILayout2d;
	import com.somerandomdude.coordy.layouts.twodee.VerticalLine;
	import flash.display.MovieClip;
	import flash.events.Event;
	import pages.Pages;
	import ui.media.DiaporamaItem;
	
	/**
	 * ...
	 * @author usual
	 */
	public class Diaporama extends MovieClip 
	{
		private var _xmlData:XML;
		private var _layout:ILayout2d;
		private var _sens:String;
		private var _assetPage:String;
		//prend en parametre le sens ( h ou v), et le nom de la page dont seront extrait les assets
		public function Diaporama(sens:String='h',assetsPage:String=Pages.PHOTOS) 
		{
			_sens = sens;
			_assetPage = assetsPage;
			addEventListener(Event.ADDED_TO_STAGE, _build);
			_xmlData = Gaia.api.getPage(_assetPage).node;
		}
		
		public function destroy():void 
		{
			stage.removeEventListener(Event.RESIZE, _resize);
			if (this.parent != null) parent.removeChild(this);
		}
		
		private function _build(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, _build);
			addItems();
			_resize();
			stage.addEventListener(Event.RESIZE, _resize);
		}
		
		private function _resize(e:Event=null):void 
		{
			var ln:uint = _layout.nodes.length;
			for (var i:int = 0; i < ln; i++) 
			{
				DiaporamaItem(_layout.nodes[i].link).resize();
			}
			if(_sens=='h')HorizontalLine(_layout).hPadding = -(_layout.nodes[0].link.width - DiaporamaItem(_layout.nodes[0].link).itemWidth);
			if(_sens=='v')VerticalLine(_layout).vPadding = -(_layout.nodes[0].link.height - DiaporamaItem(_layout.nodes[0].link).itemHeight);
			_layout.updateAndRender();
		}
		
		private function addItems():void 
		{
			var ln:int = _xmlData.asset.length();
			if(_sens=='h')_layout = new HorizontalLine(0);
			if(_sens=='v')_layout = new VerticalLine(0);
			for (var i:int = 0; i < ln; i++) 
			{
				if (_xmlData.asset[i].@type == "sprite")
				{
					var item:DiaporamaItem = new DiaporamaItem(_xmlData.asset[i],_sens,_assetPage);
					addChild(item);
					_layout.addNode(item);
				}
			}
			
		}
	}

}